<template>
  <div class="main">
    <div class="chart" data-item="1">
      <span>通频振幅（μm）</span>
      <chart-item
        type="tp"
        color="#7dbffeff"
        :data="tpObj.data"
        :x-data="tpObj.x"
      />
    </div>
    <div class="chart" data-item="2">
      <span
        ><span v-if="sig === 3">0.43</span
        ><span v-else-if="sig === 4">0.65</span
        ><span v-else>1</span>x振幅（μm）</span
      >
      <chart-item
        type="zf"
        color="#f08d22ff"
        :data="zfObj.data"
        :x-data="zfObj.x"
      />
    </div>
    <div class="chart" data-item="3" v-if="sig !== 3 && sig !== 4">
      <span>1x相位角</span>
      <chart-item
        type="xwj"
        color="#6462daff"
        :data="xwjObj.data"
        :x-data="xwjObj.x"
      />
    </div>
    <div class="chart" data-item="4">
      <span>频谱振幅</span>
      <chart-item
        type="py"
        color="#4eba64ff"
        :data="pyObj.data"
        :x-data="pyObj.x"
      />
    </div>
  </div>
</template>
<script lang="ts">
import {
  computed,
  defineComponent,
  onMounted,
  onUnmounted,
  reactive,
  watch,
} from 'vue'
import ChartItem from '@/components/charts/chartItem.vue'
import useMainStore from '@/store/main'
import { storeToRefs } from 'pinia'
import useExtraRouter from '@/libs/ExtraRouter'
import { getPy, getRealChart, getTp, getXwj, getZf, getZs } from '@/api'
import { alarmProcessor } from '@/utils/alarmProcessor'

export default defineComponent({
  name: 'Charts',
  components: { ChartItem },
  props: {},
  setup() {
    const store = useMainStore()
    const { sig, isReal } = storeToRefs(store)
    const router = useExtraRouter()

    const compId: any = computed(() => {
      return router.getMeta().compName
    })

    // 图表数据
    let zfObj = reactive<{ x: string[]; data: number[] }>({
        x: [],
        data: [],
      }),
      xwjObj = reactive<{ x: string[]; data: number[] }>({
        x: [],
        data: [],
      }),
      tpObj = reactive<{ x: string[]; data: number[] }>({
        x: [],
        data: [],
      }),
      pyObj = reactive<{ x: string[]; data: number[] }>({
        x: [],
        data: [],
      }),
      apiIndex = 1,
      realIndex = 0
    // 横轴数据
    // const xData = getTimeAry()

    // 真实数据可能超过60记录参数
    const minObj = {
      data: 0,
      time: 0,
      num: 60,
    }
    // 模拟数据数量
    const mockNum = 60,
      mockTime = 500,
      realTime = 180000

    function clearData() {
      apiIndex = 1
      realIndex = 0
      zfObj.data = []
      zfObj.x = []
      xwjObj.data = []
      xwjObj.x = []
      tpObj.data = []
      tpObj.x = []
      pyObj.data = []
      pyObj.x = []
    }

    function getData() {
      if (isReal.value) {
        // clearData()
        getRealChart(compId.value, realIndex > 0 ? 1 : 60).then(({ data }) => {
          if (data.alarm >= 1) alarmProcessor(data.alarm)
          if (realIndex === 0) {
            const _zfData = createNullAry(60)
            const _xwjData = createNullAry(60)
            const _tpData = createNullAry(60)
            const sortData = data.data.sort((a: any, b: any) => {
              const at = new Date(a.dateTime).getTime(),
                bt = new Date(b.dateTime).getTime()
              return bt - at
            })
            for (let i = 0; i < sortData.length; i++) {
              _zfData[_zfData.length - 1 - i] = sortData[i].zf ?? 0
              _xwjData[_xwjData.length - 1 - i] = sortData[i].xwj ?? 0
              _tpData[_tpData.length - 1 - i] = sortData[i].tp ?? 0
            }

            let maxTime = sortData[0].dateTime

            minObj.time = new Date(maxTime).getTime()

            zfObj.data = _zfData
            xwjObj.data = _xwjData
            tpObj.data = _tpData

            const tAry = getTimeAry(3, maxTime, minObj.num)
            zfObj.x = tAry
            xwjObj.x = tAry
            tpObj.x = tAry

            setPyObj(data.data[0])

            setTimeout(() => {
              getData()
            }, 50)
          } else {
            const _data = data.data
            const time = new Date(_data.dateTime).getTime() - 10800000
            if (time < minObj.time) {
              zfObj.data.shift()
              zfObj.x.shift()
              xwjObj.data.shift()
              xwjObj.x.shift()
              tpObj.data.shift()
              tpObj.x.shift()
            } else {
              minObj.num++
            }
            const tAry = getTimeAry(3, _data.dateTime, minObj.num)
            zfObj.x = tAry
            xwjObj.x = tAry
            tpObj.x = tAry
            zfObj.data.push(_data.zf ?? 0)
            xwjObj.data.push(_data.xwj ?? 0)
            tpObj.data.push(_data.tp ?? 0)
            setPyObj(_data)
          }
          realIndex++
        })
      } else {
        getZs(sig.value, apiIndex).then(({ data }) => {
          if (data.alarm >= 1) alarmProcessor(data.alarm)
          store.setRunSpeedSim(data.data)
        })
        getZf(sig.value, apiIndex).then(({ data }) => {
          if (zfObj.data.length === 0) {
            zfObj.data = createNullAry(mockNum)
          }
          if (data.alarm >= 1) alarmProcessor(data.alarm)
          if (zfObj.data.length === mockNum) {
            zfObj.data.shift()
            zfObj.x.shift()
          }
          zfObj.data.push(data.data)
          zfObj.x = getTimeAry(1, '1999-02-02 ' + data.dateTime, mockNum)
        })
        getXwj(sig.value, apiIndex).then(({ data }) => {
          if (xwjObj.data.length === 0) xwjObj.data = createNullAry(mockNum)
          if (data.alarm >= 1) alarmProcessor(data.alarm)
          if (xwjObj.data.length === mockNum) {
            xwjObj.data.shift()
            xwjObj.x.shift()
          }
          xwjObj.data.push(data.data)
          xwjObj.x = getTimeAry(1, '1999-02-02 ' + data.dateTime, mockNum)
        })
        getTp(sig.value, apiIndex).then(({ data }) => {
          if (tpObj.data.length === 0) tpObj.data = createNullAry(mockNum)
          if (data.alarm >= 1) alarmProcessor(data.alarm)
          if (tpObj.data.length === mockNum) {
            tpObj.data.shift()
            tpObj.x.shift()
          }
          tpObj.data.push(data.data)
          tpObj.x = getTimeAry(1, '1999-02-02 ' + data.dateTime, mockNum)
        })
        getPy(sig.value, apiIndex).then(({ data }) => {
          if (data.alarm >= 1) alarmProcessor(data.alarm)
          const _pyAry = data.data
          const pyAry: any[] = []
          pyObj.x = [
            '',
            '1x',
            '',
            '2x',
            '',
            '3x',
            '',
            '4x',
            '',
            '5x',
            '',
            '6x',
            '',
            '7x',
            '',
            '8x',
            '',
            '9x',
            '',
            '10x',
          ]
          if ([0, 3, 4].includes(sig.value)) {
            if (sig.value === 3) pyObj.x[0] = '0.43x'
            else if (sig.value === 4) pyObj.x[0] = '0.65x'
            else if (sig.value === 0) pyObj.x[0] = '0.5x'
            _pyAry.forEach((item: any, index: number) => {
              pyAry.push(item)
              if (index !== 0 && index !== _pyAry.length - 1) pyAry.push(0)
            })
          } else {
            _pyAry.forEach((item: any) => {
              pyAry.push(0)
              pyAry.push(item)
            })
          }
          pyObj.data = pyAry
        })
        apiIndex++
      }
    }

    let intIndex: any = 0

    function intervalData() {
      clearData()
      window.clearInterval(intIndex)
      if (!isReal.value && sig.value === 0) return
      getData()

      let t = mockTime
      if (isReal.value) t = realTime
      intIndex = setInterval(() => {
        getData()
        if (apiIndex >= mockNum) {
          clearInterval(intIndex)
          apiIndex = 1
        }
      }, t)
    }

    function setPyObj(data: any) {
      const _pyObj = data,
        _pyAry = []
      for (let k in _pyObj) {
        if (k.startsWith('py')) {
          _pyAry.push(_pyObj[k] ?? 0)
        }
      }
      pyObj.x = [
        '0.5x',
        '1x',
        '',
        '2x',
        '',
        '3x',
        '',
        '4x',
        '',
        '5x',
        '',
        '6x',
        '',
        '7x',
        '',
        '8x',
        '',
        '9x',
        '',
        '10x',
      ]
      for (let i = 1; i < _pyAry.length; i++) {
        pyObj.data.push(0)
        pyObj.data.push(_pyAry[i] ?? 0)
        // pyObj.data.push(Math.random() * 80)
      }
      pyObj.data[0] = _pyAry[0] ?? 0
    }

    onMounted(() => {
      intervalData()
    })
    onUnmounted(() => {
      window.clearInterval(intIndex)
    })
    watch(
      () => isReal.value,
      () => {
        intervalData()
        if (isReal.value) {
          minObj.num = 60
          minObj.time = 0
        }
      },
    )
    watch(
      () => sig.value,
      () => {
        intervalData()
        realIndex = 0
      },
    )

    return { zfObj, tpObj, xwjObj, pyObj, sig }
  },
})
function getTimeAry(h: number, time: string, num: number) {
  const t = new Date(time).getTime()
  const interval = (h * 60 * 60 * 1000) / num
  const ary: string[] = []
  for (let i = 0; i < num; i++) {
    const _t = new Date(t - i * interval)
    const h = ('0' + _t.getHours()).slice(-2)
    const m = ('0' + _t.getMinutes()).slice(-2)
    ary.unshift(h + ':' + m)
  }
  return ary
}

function createNullAry(num: number) {
  const a = []
  for (let i = 0; i < num; i++) {
    a.push(null)
  }
  return a as any
}
</script>

<style scoped lang="scss">
.main {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  padding: 10px 5px 5px;

  .chart {
    display: flex;
    flex-direction: column;
    width: 100%;
    height: 25%;
    overflow: hidden;

    &[data-item='1'] {
      color: #7dbffeff;
    }

    &[data-item='2'] {
      color: #f08d22ff;
    }

    &[data-item='3'] {
      color: #6462daff;
    }

    &[data-item='4'] {
      color: #4eba64ff;
    }

    > span {
      flex-shrink: 0;
      margin-left: 10px;
    }
  }
}
</style>
